import Router from 'koa-router'
import {createListener} from "../utils/download"
import config from '../project.config.json'
import {Stream} from "stream";

const lzy = config.shareUrl
const router = new Router()

router.get('/:imgId', async context => {
  const imgId = context.params.imgId

  const url = await new Promise<string>(resolve => {
    const start = createListener({
      redirect: true,
      onEnd: (url) => resolve(url),
    })
    start({url: lzy + '/' + imgId})
  })

  context.set('Content-Type', 'application/octet-stream')
  context.redirect(url)

  // 使用本机下载
  // const stream = new Stream.PassThrough()
  // context.body = stream
  // await new Promise<string>(resolve => {
  //   const start = createListener({
  //     redirect: false,
  //     onStart: (headers) => {
  //       // console.log(headers)
  //       if (headers['content-disposition']) {
  //         for (const suffix of config.suffixes) {
  //           if (headers['content-disposition'].endsWith(suffix)) {
  //             headers['content-disposition'] = headers['content-disposition'].replace(new RegExp(`\\${suffix}$`), '')
  //             break
  //           }
  //         }
  //       }
  //       context.set(headers)
  //     },
  //     onData: chunk => stream.push(chunk),
  //     onEnd: resolve,
  //   })
  //   start({url: lzy + '/' + imgId})
  // })
})

export = router
